package com.ruoyi.optimization.controller;

import com.alibaba.fastjson2.JSON;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.font.FontProvider;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.optimization.domain.OptimizationRecord;
import com.ruoyi.optimization.domain.optimizeRes;
import com.ruoyi.optimization.service.IOptimizationRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * 优化记录Controller
 * 
 * @author ruoyi
 * @date 2025-05-13
 */
@RestController
@RequestMapping("/optimization/record")
public class OptimizationRecordController extends BaseController
{
    @Autowired
    private IOptimizationRecordService optimizationRecordService;

    @Autowired
    private TemplateEngine templateEngine;
    /**
     * 查询优化记录列表
     */
    @PreAuthorize("@ss.hasPermi('optimization:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(OptimizationRecord optimizationRecord)
    {
        startPage();
        List<OptimizationRecord> list = optimizationRecordService.selectOptimizationRecordList(optimizationRecord);
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('optimization:record:list')")
    @GetMapping("/listOptimizationRecordBycreateBy")
    public TableDataInfo listOptimizationRecordBycreateBy()
    {
        startPage();
        List<OptimizationRecord> list = optimizationRecordService.listOptimizationRecordBycreateBy(getUsername());
        return getDataTable(list);
    }

    /**
     * 导出优化记录列表
     */
    @PreAuthorize("@ss.hasPermi('optimization:record:export')")
    @Log(title = "优化记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OptimizationRecord optimizationRecord)
    {
        List<OptimizationRecord> list = optimizationRecordService.selectOptimizationRecordList(optimizationRecord);
        ExcelUtil<OptimizationRecord> util = new ExcelUtil<OptimizationRecord>(OptimizationRecord.class);
        util.exportExcel(response, list, "优化记录数据");
    }
    @PreAuthorize("@ss.hasPermi('optimization:record:export')")
    @Log(title = "优化记录", businessType = BusinessType.EXPORT)
    @GetMapping(value = "/generatePdf/{id}")
    public ResponseEntity<byte[]> exportPdf(@PathVariable("id") Long id) throws Exception {

        OptimizationRecord resData= optimizationRecordService.selectOptimizationRecordById(id);
        String htmlContent = "没有数据";

        if (resData!=null){
            optimizeRes res = JSON.parseObject(resData.getData(), optimizeRes.class);
            htmlContent = generateHtmlFromTemplate(res);
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // 创建字体提供器并添加中文字体
        FontProvider fontProvider = new FontProvider();

        // 从资源流加载字体

//        String fontPath = Objects.requireNonNull(getClass().getResource("/static/fonts/STFANGSO.TTF")).getPath();
        String fontPath = "/usr/local/src/service/STFANGSO.TTF";
        PdfFont chineseFont = PdfFontFactory.createFont(fontPath, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED);
        fontProvider.addFont(chineseFont.getFontProgram());

        // 设置 ConverterProperties
        ConverterProperties converterProperties = new ConverterProperties();
        converterProperties.setFontProvider(fontProvider);

        // 转换 HTML 到 PDF
        HtmlConverter.convertToPdf(htmlContent, outputStream, converterProperties);

        byte[] pdfBytes = outputStream.toByteArray();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData("attachment", "optimization_report.pdf");

        return ResponseEntity.ok().headers(headers).body(pdfBytes);
    }

    private String generateHtmlFromTemplate(optimizeRes res) {
        Context context = new Context();
        context.setVariable("res", res);
        return templateEngine.process("report_template", context);
    }
    /**
     * 获取优化记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('optimization:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(optimizationRecordService.selectOptimizationRecordById(id));
    }

    /**
     * 新增优化记录
     */
    @PreAuthorize("@ss.hasPermi('optimization:record:add')")
    @Log(title = "优化记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OptimizationRecord optimizationRecord)
    {
        return toAjax(optimizationRecordService.insertOptimizationRecord(optimizationRecord));
    }

    /**
     * 修改优化记录
     */
    @PreAuthorize("@ss.hasPermi('optimization:record:edit')")
    @Log(title = "优化记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OptimizationRecord optimizationRecord)
    {
        return toAjax(optimizationRecordService.updateOptimizationRecord(optimizationRecord));
    }

    /**
     * 删除优化记录
     */
    @PreAuthorize("@ss.hasPermi('optimization:record:remove')")
    @Log(title = "优化记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(optimizationRecordService.deleteOptimizationRecordByIds(ids));
    }
}
